package com.younion.action.manage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.cache.support.SimpleValueWrapper;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.younion.business.ICustomerService;
import com.younion.business.IMemberCardService;
import com.younion.business.IMessageService;
import com.younion.business.IMsgTemplateService;
import com.younion.business.IRegisterUserService;
import com.younion.business.IRolesService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.MsgStatus;
import com.younion.common.constants.MsgType;
import com.younion.common.constants.RoleType;
import com.younion.common.constants.Schedule;
import com.younion.common.constants.Status;
import com.younion.common.constants.TemplateScope;
import com.younion.common.constants.TemplateTargetType;
import com.younion.common.exception.BaseException;
import com.younion.common.paginator.Paginator;
import com.younion.common.system.SystemConfig;
import com.younion.util.YounionUtil;
import com.younion.vo.CustomerVO;
import com.younion.vo.MemberCardVO;
import com.younion.vo.MessageVO;
import com.younion.vo.MsgTemplateVO;
import com.younion.vo.RegisterUserVO;
import com.younion.vo.RolesVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author Joe Chen
*/
public class MessageAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	protected static final Log logger = LogFactory.getLog(MessageAction.class);

	private IMessageService messageService = null;

	private MessageVO messageVO = new MessageVO();

	private List<MessageVO> messageList;//  结果集列表
	
	private List<Schedule> schedules = Arrays.asList(Schedule.values());
	
	private List<MsgType> msgTypes = Arrays.asList(MsgType.values());
	
	private List<MsgStatus> statuses = Arrays.asList(MsgStatus.values());
	
	private List<MsgTemplateVO> templates = null;
	
	private Collection membercards = null;
	
	@Autowired
	private IRolesService rolesService = null;
	
	@Autowired
	private IMsgTemplateService msgTemplateService = null;
	@Autowired
	private IMemberCardService memberCardService = null;
	//@Autowired	
	//private ICustomerAccountService customerAccountService = null;
	@Autowired	
	private ICustomerService customerService = null;
	
	@Autowired
	private IRegisterUserService registerUserService = null;
	
	@Autowired
	private SimpleCacheManager simpleCacheManager = null;
	
	private String memberIds = null;
	/**
	 * 列表：翻页区；数据区
	 */
	@RequiresPermissions("listMessage")
	@SuppressWarnings("unchecked")
	public String listMessage() {
		try {
			Map paramMap = null;
			if (messageVO != null) {
				if("".equals(messageVO.getUsers()))
					messageVO.setUsers(null);
				if(getSessionUser().getCustomer() != null){
					messageVO.setCustomer(getSessionUser().getCustomer());
				}
				if(messageVO.getTemplate() != null && messageVO.getTemplate().getId() < 0)
					messageVO.setTemplate(null);
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(messageVO));
			}
			// 获取总记录数
			int total = messageService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			messageList = messageService.get(paramMap, paginator);
			//保存分页对象
			this.savaPaginator(paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	@RequiresPermissions("addMessage")
	public String addMessage() {
		String pkId = request.getParameter("ids");
		messageVO.setUsers(pkId);
		setupTemplates();
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	@RequiresPermissions("editMessage")
	public String editMessage() {
		try {
			messageVO = messageService.getById(messageVO.getId().toString());
			setupTemplates();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 保存动作
	 */
	@RequiresPermissions("saveMessage")
	public String saveMessage() {
		List<MemberCardVO> noAllowList = new ArrayList<MemberCardVO>();
		List<MemberCardVO> memberCards = Lists.newArrayList();
		try {
			if(messageVO.getId() != null){
				messageService.save(messageVO);
				this.addLog(3, "修改发送信息：["+this.messageVO.getId()+"]", "修改发送信息",getSessionUser());
				return SUCCESS;
			}
			if(messageVO.getUsers() != null && "ALL".equalsIgnoreCase(messageVO.getUsers())){
				SimpleValueWrapper simplevaluewrapper = (SimpleValueWrapper) simpleCacheManager.getCache(CACHE_KEY).get(getSessionUser().getId());
				Map paramMap = (Map) simplevaluewrapper.get();
				if(getSessionUser().getCustomer() != null)
					paramMap.put("customerId", getSessionUser().getCustomer().getId());
				Collection membercards = memberCardService.getByMap(paramMap);
				memberCards.addAll(membercards);
			}else{
				memberCards = memberCardService.selectByIds(Arrays.asList(messageVO.getUsers().split(",")));
			}
			for(MemberCardVO memberCardVO : memberCards){
				if(memberCardVO.getIsAllowPush() != null && memberCardVO.getIsAllowPush()==0){
					noAllowList.add(memberCardVO);
				}
			}
			memberCards.remove(noAllowList);
			if(memberCards.isEmpty()){
				tipMessage = "不存在符合推送条件的用户";
				request.setAttribute("tipMessage", tipMessage);
				return ERROR;
			}
			RolesVO role = rolesService.getById(getSessionUser().getRole().toString());
			if(getSessionUser().getCustomer() == null && !RoleType.SUPPER.getName().equals(role.getRoleType())){
				tipMessage = "你没有权限管理该商家";
				request.setAttribute("tipMessage", tipMessage);
				return ERROR;
			}
			CustomerVO customer = null; 
			//CustomerAccountVO customerAccount = null;
			Map paramMap = Maps.newHashMap();
			if(!RoleType.SUPPER.getName().equals(role.getRoleType())){
				customer = customerService.getById(getSessionUser().getCustomer().getId().toString());
				//customerAccount = customerAccountService.getById(customer.getCustomerAccountId().toString());
			}
			List<MessageVO> msgs = generateMsgContent(memberCards);
			String unitStr = SystemConfig.getInstance().getPropValue("sendmsg.cut.money");
			Integer unit = Integer.valueOf(unitStr);
			double money = msgs.size() * unit;
			if(customer != null ){
				if(customer.getMoney() == null || money > customer.getMoney()){
					tipMessage = "你的余额不足，请充值";
					request.setAttribute("tipMessage", tipMessage);
					return ERROR;
				}else{
					//paramMap.put("money", customerAccount.getMoney() - money);
					//paramMap.put("id", customerAccount.getId());
					paramMap.put("money", customer.getMoney() - money);
					paramMap.put("id", customer.getId());
				}
			}
			messageService.insertSendMsg(msgs,paramMap);
			String templateId = (messageVO.getTemplate() == null || messageVO.getTemplate().getId() == null) ? "" : messageVO.getTemplate().getId().toString();
			this.addLog(3, "发送消息：会员卡["+messageVO.getUsers()+"],模板："+ templateId, "发送消息",getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			return ERROR;
		}
		request.setAttribute("refreshNavTabId", "messageList");
		request.setAttribute("callbackType", "forward");
		request.setAttribute("dialogId", "messageDialog");
		request.setAttribute("forwardUrl", request.getContextPath()+"/memberCard/listMemberCard.action");
		if(!noAllowList.isEmpty())
			tipMessage ="共推送"+memberCards.size()+"条消息，因用户不允许推送而被过滤"+noAllowList.size()+"条消息";
		return SUCCESS;
	}

	private List<MessageVO> generateMsgContent(List<MemberCardVO> memberCards) throws BaseException {
		List<MessageVO> msgs = Lists.newArrayList();
		for(MemberCardVO card : memberCards){
			RegisterUserVO user = registerUserService.getByMemberCard(card);
			if(user != null){
				MessageVO msg = new MessageVO();
				msg.setSendTime(messageVO.getSendTime()==null?new Date():messageVO.getSendTime());
				msg.setStatus(MsgStatus.UNSEND.getName());
				msg.setTemplate(messageVO.getTemplate());
				msg.setCustomer(this.getSessionUser().getCustomer());
				msg.setUsers(card.getId().toString());
				String content = YounionUtil.generateMessageContent(messageVO.getContent(), card);
				msg.setContent(content);
	    		msg.setMobile(user.getLoginId());
	    		msg.setUsertoken(user.getUserToken());
	    		msg.setDeviceToken(user.getDeviceToken());
	    		msgs.add(msg);
	    	}
		}
		return msgs;
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("deleteMessage")
	public String deleteMessage() {
		try {
			String pkId = request.getParameter("ids");
			messageService.remove(Arrays.asList(pkId.split(",")));
			this.addLog(3, "删除发送信息：["+pkId+"]", "删除发送信息",getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "messageList");
		return SUCCESS;
	}
	/**
	 * 查看鿴
	 */
	@RequiresPermissions("viewMessage")
	public String viewMessage() {
		try {
			messageVO = messageService.getById(messageVO.getId().toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}
	
	private void setupTemplates(){
		templates = Lists.newArrayList();
		Map paramMap = Maps.newHashMap();
		try {
			//paramMap.put("status",Status.APPROVABLE.getName());
			paramMap.put("status",Status.ACTIVE.getName());
			paramMap.put("scope", TemplateScope.MSG.getName());
			paramMap.put("targetType", TemplateTargetType.COMMON.getName());
			if(getSessionUser().getCustomer() != null){
				paramMap.put("customerId", getSessionUser().getCustomer().getId());
			}
			Collection msgs = msgTemplateService.getByMap(paramMap);
			paramMap.put("scope", TemplateScope.ALL.getName());
			msgs.addAll(msgTemplateService.getByMap(paramMap));
			Iterator it  = msgs.iterator();
			while(it.hasNext()){
				templates.add((MsgTemplateVO)it.next());
			}
		} catch (BaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 发送短信
	 * @return
	 */
	@RequiresPermissions("sendMessage")
	public String sendMessage(){
		try {
			String pkId = request.getParameter("ids");
			if(pkId == null){
				tipMessage = "请选择会员卡";
				request.setAttribute("tipMessage", tipMessage);
				return ERROR;
			}else if("ALL".equalsIgnoreCase(pkId)){
				memberIds = "ALL";
			}else{
				memberIds = pkId.substring(0,pkId.length()-1);
			}
			setupTemplates();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public MessageVO getMessageVO() {
		return messageVO;
	}

	public void setMessageVO(MessageVO messageVO) {
		this.messageVO = messageVO;
	}

	public void setMessageService(IMessageService messageService) {
		this.messageService = messageService;
	}

	public List<MessageVO> getMessageList() {
		return messageList;
	}

	public void setMessageList(List<MessageVO> messageList) {
		this.messageList = messageList;
	}

	public List<Schedule> getSchedules() {
		return schedules;
	}

	public void setSchedules(List<Schedule> schedules) {
		this.schedules = schedules;
	}

	public IMessageService getMessageService() {
		return messageService;
	}

	public List<MsgType> getMsgTypes() {
		return msgTypes;
	}

	public void setMsgTypes(List<MsgType> msgTypes) {
		this.msgTypes = msgTypes;
	}

	public List<MsgTemplateVO> getTemplates() {
		if(templates == null){
			setupTemplates();
		}
		return templates;
	}

	public void setTemplates(List<MsgTemplateVO> templates) {
		this.templates = templates;
	}

	public IMsgTemplateService getMsgTemplateService() {
		return msgTemplateService;
	}

	public void setMsgTemplateService(IMsgTemplateService msgTemplateService) {
		this.msgTemplateService = msgTemplateService;
	}

	public String getMemberIds() {
		return memberIds;
	}

	public void setMemberIds(String memberIds) {
		this.memberIds = memberIds;
	}

	public IMemberCardService getMemberCardService() {
		return memberCardService;
	}

	public void setMemberCardService(IMemberCardService memberCardService) {
		this.memberCardService = memberCardService;
	}

	/*public ICustomerAccountService getCustomerAccountService() {
		return customerAccountService;
	}

	public void setCustomerAccountService(
			ICustomerAccountService customerAccountService) {
		this.customerAccountService = customerAccountService;
	}*/

	public ICustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public List<MsgStatus> getStatuses() {
		return statuses;
	}

	public void setStatuses(List<MsgStatus> statuses) {
		this.statuses = statuses;
	}

	public IRolesService getRolesService() {
		return rolesService;
	}

	public void setRolesService(IRolesService rolesService) {
		this.rolesService = rolesService;
	}

	public void setMembercards(List<MemberCardVO> membercards) {
		this.membercards = membercards;
	}

	public Collection getMembercards() {
		if(membercards == null){
			try {
				if(this.getSessionUser().getCustomer() == null){
					membercards = memberCardService.getAll();
				}else{
					Map paramMap = Maps.newHashMap();
					paramMap.put("customerId",this.getSessionUser().getCustomer().getId());
					membercards = memberCardService.getByMap(paramMap);
				}
			} catch (Exception e) {
			}
		}
		return membercards;
	}

	public void setMembercards(Collection membercards) {
		this.membercards = membercards;
	}

	public IRegisterUserService getRegisterUserService() {
		return registerUserService;
	}

	public void setRegisterUserService(IRegisterUserService registerUserService) {
		this.registerUserService = registerUserService;
	}

	public SimpleCacheManager getSimpleCacheManager() {
		return simpleCacheManager;
	}

	public void setSimpleCacheManager(SimpleCacheManager simpleCacheManager) {
		this.simpleCacheManager = simpleCacheManager;
	}
	
}